#include "../include/auth_manager.h"
#include "../include/db_manager.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <openssl/sha.h>
#include <openssl/hmac.h>

AuthManager::AuthManager() {
    // 不再使用硬编码数据，改为从数据库读取
}

std::string AuthManager::authenticate(const std::string& username, const std::string& password, const std::string& role) {
    DBManager& db = DBManager::getInstance();
    
    if (role == "admin") {
        // 从admin_login表验证管理员
        std::string query = "SELECT Password FROM admin_login WHERE Username = '" + db.escapeString(username) + "'";
        auto results = db.executeSelectQuery(query);
        
        if (!results.empty()) {
            std::string stored_password = results[0].at("Password");
            if (stored_password == password) {
                return generateToken(username, role);
            }
        }
    } else if (role == "employee") {
        // 从employee_login表验证员工
        std::string query = "SELECT Employee_passeword FROM employee_login WHERE Employee_name = '" + db.escapeString(username) + "'";
        auto results = db.executeSelectQuery(query);
        
        if (!results.empty()) {
            std::string stored_password = results[0].at("Employee_passeword");
            if (stored_password == password) {
                return generateToken(username, role);
            }
        }
    }
    
    return "";
}

std::string AuthManager::generateToken(const std::string& username, const std::string& role) {
    // 简单的token生成，实际项目中应该使用JWT
    std::string token_data = username + ":" + role + ":" + std::to_string(time(nullptr));
    
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, token_data.c_str(), token_data.length());
    SHA256_Final(hash, &sha256);
    
    std::stringstream ss;
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
    }
    
    return ss.str();
}

bool AuthManager::validateToken(const std::string& token) {
    // 简单的token验证，实际项目中应该验证JWT
    return token.length() == 64; // SHA256 hash length
}

std::string AuthManager::hashPassword(const std::string& password) {
    // 简单的密码哈希，实际项目中应该使用bcrypt或argon2
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, password.c_str(), password.length());
    SHA256_Final(hash, &sha256);
    
    std::stringstream ss;
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
    }
    
    return ss.str();
} 